package com.mofish.zbserver.common.base;


import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mofish.zbserver.common.CommonService;
import com.mofish.zbserver.common.Constants;
import com.mofish.zbserver.common.TokenUtils;
import com.mofish.zbserver.common.Utils;
import com.mofish.zbserver.common.Result;

import java.io.IOException;
import java.util.List;


@WebFilter("/*")
public class SecurityFilter implements Filter {

    public static List<String> ALLOWED_PATHS = Utils.array2List(new String[] {
    		"/img", // 图片资源
    		"/login", // 登录页面
    		"/user/login", // 登录请求
    		"register", // 注册界面
    		"/user/register", // 注册请求
    		"/common/check/login", // frame、随笔详情页，检查是否是登录状态
        	"/home", // 用户主页
        	"/common/avatar/byname", // 获取用户主页的头像
        	"/common/check/u_name",
    });

    /**
     * 需要token的请求
     */
    public static List<String> FORBIDDENED_PATHS = Utils.array2List(new String[] {
    		"/home/menu",
    });

    @Resource
    private CommonService commonService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String path = request.getServletPath();

        boolean forbiddened = false;
		for (String pathPrefix : FORBIDDENED_PATHS) {
			if (path.startsWith(pathPrefix)) {
				forbiddened = true;
				break;
			}
		}

		if (!forbiddened) {
	        for (String pathPrefix : ALLOWED_PATHS) {
	        	if (path.startsWith(pathPrefix)) {
	        		filterChain.doFilter(servletRequest,servletResponse);
	        		return;
	        	}
	        }
		}

        String clientToken = request.getHeader(Constants.HEADER_TOKEN);

        try {
            TokenUtils.verifyToken(clientToken,commonService);
        } catch (Exception e) {
            e.printStackTrace();
            Utils.outJson(response, Result.fail(Result.ERR_CODE_UNLOGIN,e.getMessage()));
            return;
        }

        try{
            filterChain.doFilter(servletRequest,servletResponse);
        }catch (Exception e) {
            e.printStackTrace();
            Utils.outJson(response, Result.fail(Result.ERR_CODE_SYS,e.getMessage()));

        }
    }

    @Override
    public void destroy() {

    }
}